package cn.semes.aop;

import cn.semes.system.domain.Log;
import cn.semes.system.mapper.LogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Date;

@Aspect
@Component
@Slf4j
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LogManager {

    @Autowired
    private LogMapper mapper;

    @Pointcut("@annotation(cn.semes.aop.LogAop)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Log log = new Log();
        // 拦截所有请求 判断出当前请求是什么方法 访问的电脑ip是多少 时间是什么时候 将数据存到数据库 日志表
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        // 获取方法上注解里面的值
        LogAop logaop = method.getAnnotation(LogAop.class);
        String name = logaop.name();
        LogManager.log.info("注解上面的name：{}",name);
        // 获取方法名称
        String methodName = method.getName();
        LogManager.log.info("方法名称：{}",methodName);
        log.setOperation(methodName);
        // 获取电脑ip
        InetAddress localHost = Inet4Address.getLocalHost();
        String hostAddress = localHost.getHostAddress();
        LogManager.log.info("电脑ip地址为：{}",hostAddress);
log.setIp(hostAddress);
        Date date = new Date();
        LogManager.log.info("时间是：{}",date);
        log.setDate(date);
        // 1.在add执行之前 获取到参数
        // 2.执行add
        mapper.add(log);
        Object proceed = pjp.proceed();
        // 3.add执行之后添加日志
        new Date();
        ///

        return proceed;

    }
}
